package com.hoyu.time.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TimeClient {
	
	private boolean status;
	
	private Socket socket;
	
	private Scanner scanner;
	
	
	public boolean start() throws UnknownHostException, IOException {
		socket = new Socket("127.0.0.1", 12345);
		scanner = new Scanner(System.in);
		status = true;
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					System.out.println("Read thread start...");
					while(status) {
						read();	
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();;

		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("Write thread start...");
				try {
					while(status) {
						write();	
					}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();;
		return status;
	}


	protected synchronized void write() throws IOException {
		BufferedReader console =new BufferedReader(new InputStreamReader(System.in)); 
		String str=console.readLine(); 
		System.out.println("Client WRITE: "+str);
		PrintWriter out=new PrintWriter(socket.getOutputStream()); 
		out.println(str); 
		out.flush(); 
		
	}


	
	private synchronized void read() throws IOException {
			InputStream is = socket.getInputStream();
			byte[] b = new byte[64];
			int l = 0;
			while((l=is.read(b, 0, b.length))>0) {
				String str = new String(b,0,l);
				System.out.println(str);
			}
		
	}
	
	public static void main(String[] args) {
		TimeClient client = new TimeClient();
		try {
			client.start();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

}
